package com.rui.study.micro.scheduler.init;

import com.rui.study.commons.util.JsonUtil;
import com.rui.study.micro.scheduler.model.Task;
import com.rui.study.micro.scheduler.service.BulletinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

import static com.rui.study.micro.scheduler.util.Constant.BULLETIN_TASK;

/**
 * @program: study_20180903
 * @description:
 * @author: Yaowr
 * @create: 2018-11-02 11:01
 **/
@Component
public class BulletinApplicationRunner implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(BulletinApplicationRunner.class);

    @Resource(name = "redisTemplate")
    private HashOperations<Serializable, String, String> redisOps;

    @Autowired
    private BulletinService bulletinService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> taskJsons = redisOps.values(BULLETIN_TASK);
        if (taskJsons != null && taskJsons.size() > 0) {
            for (String json : taskJsons) {
                Task task = JsonUtil.toObject(json, Task.class);
                bulletinService.buildScheduler(task);
                LOGGER.info("Initialized a bulletin task [{}]", json);
            }
        }
    }
}
